package com.study.demo.pdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

public class PdfUtil {

    public static void createPDF(Document document, PdfWriter writer, List<Product> products) throws IOException {
        //Document document = new Document(PageSize.A4);
        try {
            document.addTitle("sheet of product");
            document.addAuthor("scurry");
            document.addSubject("product sheet.");
            document.addKeywords("product.");
            document.open();
            PdfPTable table = createTable(writer, products);
            document.add(table);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }

    public static PdfPTable createTable(PdfWriter writer, List<Product> products) throws IOException, DocumentException {
        PdfPTable table = new PdfPTable(3);//生成一个两列的表格

        PdfPCell cell;
        int size = 20;
        Font font = new Font(BaseFont.createFont("C://Windows//Fonts//simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED));

        for (int i = 0; i < products.size(); i++) {

            cell = new PdfPCell(new Phrase(products.get(i).getUserName(), font));//产品编号
            cell.setFixedHeight(size);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(products.get(i).getPhone(), font));//产品名称
            cell.setFixedHeight(size);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(products.get(i).getReportUrl() + "", font));//产品价格
            cell.setFixedHeight(size);

            table.addCell(cell);
        }
        return table;
    }
}